package data;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import jsonobj.ClusterIDInfo;
import jsonobj.JobInfo;


import org.eclipse.jetty.websocket.WebSocket.Outbound;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


public class UserInfo {
	public String username;
	public String password;
	public String email;
	public int db_id;
	public ArrayList<JobInfo> jobs;
	public Map<String,ClusterInfo> clusters;
	ArrayList<ClusterIDInfo> cid;
	public volatile boolean isConnected = false;
	public Outbound out;
	
	public UserInfo(String username,String passwd, String email)
	{
		this.username = username;
		this.password = passwd;
		this.email = email;
		initDataStructs();
	}
	public UserInfo(String username,String passwd, String email, int id)
	{
		this.username = username;
		this.password = passwd;
		this.email = email;
		this.db_id = id;
		initDataStructs();
		
	}
	
	public UserInfo(jsonobj.RegisterInfo ri)
	{
		this.username = ri.user;
		this.password = ri.pass;
		this.email = ri.email;
		initDataStructs();
	}
	
	public void initDataStructs()
	{
		jobs = new ArrayList<JobInfo>();
		clusters = Collections.synchronizedMap(new HashMap<String,ClusterInfo>());
	}
	
	public String getPasswd() { return password;}
	
	
	public void generateClusterList(java.sql.Connection conn)
	{
		cid = new ArrayList<ClusterIDInfo>();
		Iterator<Entry<String,ClusterInfo>> it  = clusters.entrySet().iterator();
		while(it.hasNext())
		{
			ClusterIDInfo cd = new ClusterIDInfo(it.next().getValue());
			cd.setCurrentClusterStatus(conn);
			cid.add(cd);
		}
	}
	
	public String toString()
	{
		
		String data = new Gson().toJson(cid, new TypeToken<ArrayList<ClusterIDInfo>>() {}.getType());
		//data += "|"+ new Gson().toJson(jobs, new TypeToken<ArrayList<JobInfo>>() {}.getType());
		return data;
	}
	
	public ArrayList<ClusterInfo> getAllOnlineClusters()
	{
		ArrayList<ClusterInfo> cinfo = new ArrayList<ClusterInfo>();
		Iterator<Entry<String,ClusterInfo>> it  = clusters.entrySet().iterator();
		while(it.hasNext())
		{
			ClusterInfo ci = it.next().getValue();
			if(ci.isConnected)
				cinfo.add(ci);
				
		}
		return cinfo;
	}
	
	public void sendClusterInfo(java.sql.Connection conn) throws IOException
	{
		generateClusterList(conn);
		sendMessage("8|"+this.toString());
	}
	
	public synchronized void sendMessage(Object data) throws IOException
	{
		out.sendMessage(data.toString());
	}
	
	public void disconnect()
	{
		isConnected = false;
		out.disconnect();
		out = null;
	}
}
